package com.jin;

import com.jin.domain.CheckItem;
import com.jin.domain.FillItem;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class Tiankongti extends JFrame {

    private JPanel contentPane;
    private JTextField textField;


    /**
     * Create the frame.
     */
    public Tiankongti() {
        int fiveIndex = ExamResult.getIndexAndIncrement();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("第" + fiveIndex + "题");
        lblNewLabel.setBounds(10, 20, 54, 15);
        contentPane.add(lblNewLabel);

        List<FillItem> list = ItemSource.fillItems;
        int indexOfItem = new Random().nextInt(list.size());
        FillItem checkItemFive = list.get(indexOfItem);

        JTextArea textArea = new JTextArea(checkItemFive.getItemTitle());
        textArea.setBounds(10, 66, 550, 24);
        contentPane.add(textArea);

        JLabel lblNewLabel_1 = new JLabel("多个空以逗号分隔");
        lblNewLabel_1.setBounds(0, 127, 54, 15);
        contentPane.add(lblNewLabel_1);

        textField = new JTextField();
        textField.setBounds(0, 166, 500, 21);
        contentPane.add(textField);
        textField.setColumns(10);

        JButton btnNewButton = new JButton("提交作答");
        btnNewButton.setBounds(158, 228, 93, 23);
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String v = textField.getText();
                boolean result = checkEqual(v, checkItemFive.getAnswers());
                if (result) {
                    ExamResult.add("第" + fiveIndex + "题:正确");
                } else {
                    ExamResult.add("第" + fiveIndex + "题:错误");
                    ExamResult.add("正确答案:" + Arrays.toString(checkItemFive.getAnswers()));
                }

                JOptionPane.showMessageDialog(contentPane, ExamResult.info(),
                        "考试结果", JOptionPane.WARNING_MESSAGE);

            }
        });
        contentPane.add(btnNewButton);
    }

    private boolean checkEqual(String v, String[] answers) {
        if (v == null || "".equals(v)) {
            return false;
        }
        String[] arr = v.split(",");
        for (int i = 0; i < answers.length; i++) {
            if (!answers[i].equals(arr[i])) {
                return false;
            }
        }
        return true;
    }
}
